﻿using Server.Constant;
using Server.Enum;
using Server.Framework.Message;
using Server.Framework.Processor;
using Server.Framework.Service;
using Server.Framework.Socket;
using Server.Message.Request;
using Server.Message.Response;
using Server.Model;
using Server.OptExp;
using Server.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Server.Processor
{
    /// <summary>
    /// Author: Leil
    /// Description: 顶级菜单列表请求处理
    /// CreateTime: 2020/5/31 1:09:15
    /// </summary>
    [ProcessorAttr(MessageId.REQUEST_LOGIN)]
    class LoginProcessor : IProcessor
    {
        public void Process(ProtobufAppSession session, RequestBaseMessage message)
        {
            if (message is LoginReq msg)
            {
                bool loginFlag = false;
                UserDao user = null;
                string sql = $@"SELECT
	* 
FROM
	SYS_USER
	INNER JOIN ( SELECT LISTAGG ( ROLE_ID, ',' ) ROLE_IDS, USER_ID FROM SYS_USER_ROLE GROUP BY USER_ID ) ROLE_IDS_GROUP ON SYS_USER.ID = ROLE_IDS_GROUP.USER_ID 
WHERE
	DEL_FLAG = 1 
	AND STATUS = 1 
	AND LOGIN_NAME = '{msg.Username}'";
                try
                {
                    DBService.Instance().ExecuteQuery(sql, reader =>
                    {
                        LoginResp resp = new LoginResp(MessageId.RESPONSE_LOGIN);
                        if (reader.Read())
                        {
                            user = new UserDao()
                            {
                                ID = Convert.ToInt32(reader["ID"]),
                                OrgId = Convert.ToInt32(reader["ORG_ID"]),
                                LoginName = reader["LOGIN_NAME"].ToString(),
                                Password = reader["PASSWORD"].ToString(),
                            };
                            string roleIds = reader["ROLE_IDS"].ToString();
                            int[] roleIdArr = Array.ConvertAll(roleIds.Split(','), s => int.Parse(s));
                            user.RoleIds.AddRange(roleIdArr);
                            if (string.Equals(user.Password, msg.Password))
                            {
                                if (UserService.Instance().HasUserSession(user.ID))
                                {
                                    resp.Code = 500;
                                    resp.ErrMsg = "该用户已经登录";
                                }
                                else
                                {
                                    // 登录成功，将user存储到session中
                                    session.User = user;
                                    // 将用户添加到内存中
                                    UserService.Instance().AddUserSession(user.ID, session);
                                    resp.Code = 200;
                                    resp.LoginUser = user;
                                    loginFlag = true;
                                }
                            } else
                            {
                                resp.Code = 500;
                                resp.ErrMsg = "密码错误";
                            }
                        } else
                        {
                            resp.Code = 500;
                            resp.ErrMsg = "没有找到用户";
                        }
                        session.Send(resp);
                    });
                }
                catch (CommonOptException e)
                {
                    Console.WriteLine(e.Message);
                }
                if (loginFlag && user != null)
                {
                    LoginLogService.Instance().AddLoginLog(user.ID, session.RemoteEndPoint.ToString());
                }
            }
        }
    }
}
